//
//  YYLHomeViewModel.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/3/31.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit

class YYLHomeViewModel: NSObject {

    //VM接收数据
    lazy var originalVMArray: [YYLOriginalViewModel] = [YYLOriginalViewModel]()
    //获取首页数据
    func requestHomeData(isPullUp:Bool, callBack:@escaping ((Bool,String)->())) {
        
        //默认的上拉加载的微博id
        var max_id: Int64 = 0
        //默认的下拉刷新的微博id
        var since_id: Int64 = 0
        
        if isPullUp {
            max_id = originalVMArray.last?.homeModel?.id ?? 0
            if max_id > 0 {
            max_id -= 1
            }
        } else {
        
        since_id = originalVMArray.first?.homeModel?.id ?? 0
        }
        
        var message: String = "没有加载到微博数据"
        
        let accessToken = YYLUserAccountViewModel.shareViewModel.userAccount?.access_token
        
        YYLNetTools.sharedTools.requestHomeData(access_token: accessToken!, max_id: max_id, since_id: since_id) { (response, error) in
            
            if error != nil {
                print("首页数据请求异常error：\(error)")
                callBack(false, message)
                return
            }
            
            //代码到这里表示首页数据请求正常
            guard let dic = response as? [String: Any] else {
                print("首页请求的数据异常")
                callBack(false, message)
                return
            
            }
            
            let array = dic["statuses"]
            
            let dataArray = NSArray.yy_modelArray(with: YYLHomeModel.self, json: array!) as! [YYLHomeModel]
            //        print(dataArray)
            var tempArray: [YYLOriginalViewModel] = [YYLOriginalViewModel]()
            
            for data in dataArray {
                let originalVM = YYLOriginalViewModel()
                originalVM.homeModel = data
                tempArray.append(originalVM)
            
            }
//            self.originalVMArray = tempArray
            if isPullUp {
            self.originalVMArray.append(contentsOf: tempArray)
            } else {
            
            self.originalVMArray.insert(contentsOf: tempArray, at: 0)
            }
            
            if tempArray.count > 0 {
            message = "刷新了\(tempArray.count)条数据"
            }
            callBack(true, message)
        }
        
    }
    
}
